<?php

/**
 * The job description class for reindexing the search index via the Queued Jobs 
 * SilverStripe module.
 *
 * @package lucene-silverstripe-module
 * @author Darren Inwood <darren.inwood@chrometoaster.com>
 */
class LuceneReindexJob extends AbstractQueuedJob implements QueuedJob {

    public function __construct() {
        // Make sure db is set up for large blobs of data...
        mysql_query('SET GLOBAL net_buffer_length='.round(QueuedJobService::$memory_limit/2000));
        mysql_query('SET GLOBAL max_allowed_packet='.round(QueuedJobService::$memory_limit/2));
    }

    public function getTitle() {
        return _t('Lucene.ReindexJobTitle', 'Rebuild the Lucene search engine index');
    }

    public function getSignature() {
        return 'LuceneReindexJob';
    }

    public function setup() {
        $lucene =& Lucene::singleton();
        // Wipe current index
        $lucene->wipeIndex();
        $this->jobData = $lucene->getAllIndexableObjects();
        $this->totalSteps = count($this->jobData);
        $this->currentStep = 0;
    }

    public function process() {
        $lucene =& Lucene::singleton();

        // if there's no more, we're done!
        if (!count($this->jobData)) {
            $this->isComplete = true;
            $lucene->commit();
            $lucene->close();
            return;
        }
        
        $this->currentStep++;
        
        $item = array_shift($this->jobData);
    
        $obj = DataObject::get_by_id($item[0], $item[1]);

        $lucene->backend->doIndex($obj);

        if (!count($this->jobData)) {
            $this->isComplete = true;
            $lucene->commit();
            $lucene->close();
            return;
        }    
    }

}


